const zbActionSheet = function(){

    this.instance = '';
    this.confirmCallBack = null;
    this.clickListCallBack = [];

    this.init = function (objName, title='') {
        this.instance = objName;
        this.initCss(objName);
        this.initTpl(objName);
        document.getElementById('zbASTitle').innerText = title;
    }

    //浮层模板
    this.tpl = '<div id="zbAS" class="zb-flex-col-bottom zb-flex-nowrap zb-width-r100">\
        <div id="zbASMask" class="zb-flex-grow1" onclick="{objName}.hide()"></div>\
        <div id="zbASBox" class="zb-flex-col-between zb-flex-stretch">\
          <div id="zbASTitle" class="zb-text-center"></div>\
          <div id="zbASBody" class="zb-scroll">\
            <div id="zbASSubBody"></div>\
          </div>\
          <div id="zbASFooter" class="zb-flex-row-around zb-flex-center">\
           <div class="zbASBtn" id="zbASBtnCancel" onclick="{objName}.hide()">取消</div>\
           <div class="zbASBtn" id="zbASBtnConfirm" onclick="{objName}.confirm()">确认</div>\
          </div>\
         </div>\
         <input type="hidden" id="zbInput" value="">\
        </div>';

    this.htmlToNode = function (html) {
        let div = document.createElement('div');
        let pos = html.indexOf('<'); //避免开头有空白
        div.innerHTML = html.substring(pos);
        //return div.childNodes;
        // return div.children;
        return div.firstChild;
    }

    this.hide = function () {
        document.getElementById('zbAS').style.height = 0;
        document.getElementById('zbASBody').innerHTML = '';
        this.confirmCallBack = null;
    }

    this.show = function () {
        document.getElementById('zbAS').style.height = '100%';
    }

    this.confirm = function () {
        if (typeof this.confirmCallBack == 'function') {
            this.confirmCallBack();
        } else {
            this.hide();
        }
    }

    //生成样式
    this.initCss = function() {
        let flag = document.getElementById('zbAS');
        if (flag == null) {

            let style = document.createElement('style');
            style.innerText =
                '.zb-flex-col-top {display:flex;flex-direction:column;justify-content:flex-start}'+
                '.zb-flex-col-bottom {display:flex;flex-direction:column;justify-content:flex-end}'+
                '.zb-flex-col-between {display:flex;flex-direction:column;justify-content:space-between}'+
                '.zb-flex-col-center {display:flex;flex-direction:column;justify-content:center}'+
                '.zb-flex-col-around {display:flex;flex-direction:column;justify-content:space-around}'+
                '.zb-flex-row-center {display:flex;flex-direction:row;justify-content:center}'+
                '.zb-flex-row-around {display:flex;flex-direction:row;justify-content:space-around}'+
                '.zb-flex-row-between {display:flex;flex-direction:row;justify-content:space-between}'+
                '.zb-flex-stretch {align-items:stretch}'+
                '.zb-flex-center {align-items:center}'+
                '.zb-flex-grow1 {flex-grow:1}'+
                '.zb-flex-nowrap {flex-wrap:nowrap}'+
                '.zb-text-center {text-align:center}'+
                '.zb-scroll-x {overflow-x:scroll; white-space: nowrap;}'+
                '.zb-scroll-x::-webkit-scrollbar {display:none}'+
                '.zb-scroll-y {overflow-y:visible; white-space: nowrap;}'+
                '.zb-scroll-y::-webkit-scrollbar {display:none}'+
                '.zb-scroll{overflow:scroll; white-space: nowrap;}'+
                '.zb-scroll::-webkit-scrollbar {display:none}'+
                '.zb-width-r100{width:100%;}'+
                '.zb-height-r100{height:100%;}'+
                '#zbAS{position:fixed;top:0;height:0;z-index:200;overflow:hidden;background-color:rgba(0,0,0,0.4);}'+
                '#zbASMask{}'+
                '#zbASBox{max-height:90%;background-color:#fff;border-top-left-radius:10px;border-top-right-radius:10px;}'+
                '#zbASTitle{height:40px;line-height:40px;font-size:20px;border-bottom:1px solid #eeeeee;}'+
                '#zbASBody{padding:5px;min-height:100px;}'+
                '#zbASSubBody{width:max-content; min-width:100%; min-height:100%}'+
                '#zbASFooter{padding:5px;border-top:1px solid #eeeeee;height:40px;line-height:40px;}'+
                '.zbASBtn{width:50%;font-size:20px;text-align:center;}'+
                //'.zb-list{height:max-content;min-height:100%;flex-grow:1;flex-shrink:0;}'+
                '.zb-list{flex-grow:1;flex-shrink:0;}'+
                '.zb-list-item{margin:8px;height:30px;font-size:18px;text-align:center;flex-grow:1;flex-shrink:0;}'+
                '.zb-input{width:100%; height:100%;}'+
                '.zb-textarea{width:100%; height:100%; min-height:100px;}'+
                '.zb-text{width:100%; max-width:100%; height:100%; min-height:100px; word-wrap:break-word;}'+
                '.zb-response{background-color:#eee}'+
                '.response {animation:bg_color 1s;}'+
                '@keyframes bg_color {from{background:#eee;} to{background:#fff;}}'+
                '@-webkit-keyframes bg_color {from{background:#eee;} to{background:#fff;}}'
            ;

            let head = document.getElementsByTagName('head')[0];
            head.appendChild(style);
        }
    }

    //创建html
    this.initTpl = function (objName) {
        let flag = document.getElementById('zbAS');
        if (flag == null) {
            let body = document.getElementsByTagName('body')[0];
            this.tpl = this.tpl.replace(/\{objName\}/g, objName);
            let node = this.htmlToNode(this.tpl);
            body.appendChild(node);
        }
    }

    //记录点击的list值
    this.changeListParams = function (obj) {
        document.getElementById('zbInput').value = obj.getAttribute('data-params');
        // obj.classList.toggle('response');
        obj.setAttribute('data-clicked', '1');
        obj.classList.add('zb-response');

        //背景色显示一段时间再消失
        setTimeout(function(){
            let list = document.getElementsByClassName('zb-response');
            for (let i = 0; i < list.length; i++) {
                if (list[i].getAttribute('data-clicked') == 1) {
                    list[i].classList.remove('zb-response');
                }
            }

        }, 500);

        for (let i=0; i<this.clickListCallBack.length; i++) {
            if (typeof this.clickListCallBack[i] == 'function') {
                this.clickListCallBack[i](obj);
            }
        }
    }

    this.getListParams = function () {
        let str = document.getElementById('zbInput').value;
        str = decodeURIComponent(str);
        return JSON.parse(str)
    }

    //添加纵向列表数据
    this.addList = function(data) {
        let tplList = '<div class="zb-list zb-flex-col-around overflow-y" id="{list_id}">{list_item}</div>';
        let tplListItem = '<div class="zb-list-item zb-flex-col-center" data-params="{params}" onclick="'+this.instance+'.changeListParams(this)">{name}</div>';

        let dataBody = document.getElementById('zbASSubBody');
        dataBody.className = 'zb-flex-row-center';

        let listData = [];
        let arrListId = [];
        for (let i=0; i<data.length; i++) {
            let listValues = data[i]['values'];
            let params = data[i]['params'];
            let listId = params['id'];

            if (listId) {
                //如果页面中已经存在id=listId的列表, 先删掉
                let element=document.getElementById(listId);
                if (element) {
                    console.log('已存在节点 #'+listId);
                    element.parentNode.removeChild(element);
                }

                //如果当前data中有重复的id只会加载一次
                if (arrListId.indexOf(listId) !== -1) {
                    continue;
                } else {
                    arrListId.push(listId);
                }
            }

            // 每一列的值
            let items = this.repeatString(tplListItem, listValues, function(row){

                let val = row.toString();
                let args = {};
                for (let k in params) {
                    args[k] = params[k];
                }

                if (val.indexOf(':') === -1) {
                    args['name'] = val;
                    args['value'] = val;
                } else {
                    let tmp = val.split(':');
                    args['name'] = tmp[0];
                    args['value'] = tmp[1];
                }

                args['params'] = encodeURIComponent(JSON.stringify(args));

                return args;
            });

            listData.push({list_id:listId, list_item: items});

        }

        //组装每一列
        let listHtml = this.repeatString(tplList, listData);

        //追加到zbASSubBody中
        dataBody.innerHTML += listHtml;

    }

    this.addInput = function (config) {
        let box = document.getElementById('zbASSubBody');
        box.className= '';
        box.className = 'zb-flex-col-center';

        let input = document.createElement(config['tagName']);
        let defaultValue = (config['defaultValue']) ? config['defaultValue'] : '';
        input.setAttribute('value', defaultValue);
        input.setAttribute('type', 'text');
        input.setAttribute('id', config['id']);
        input.setAttribute('data-params', encodeURIComponent(JSON.stringify(config['params'])));
        //input.setAttribute('oninput', 'oninput="'+config['func']+'();"');
        input.classList.add('zb-input');

        if (config['maxlength'] !== undefined) {
            input.setAttribute('maxlength', config['maxlength']);
        }

        box.appendChild(input);

    }

    this.addTextarea = function (config) {
        let box = document.getElementById('zbASSubBody');
        box.className= '';
        box.className = 'zb-flex-col-center';

        let input = document.createElement('textarea');
        input.setAttribute('id', config['id']);
        input.setAttribute('maxlength', config['maxlength']);
        input.setAttribute('data-params', encodeURIComponent(JSON.stringify(config['params'])));
        input.innerHTML = (config['defaultValue']) ? config['defaultValue'] : '';
        //input.setAttribute('oninput', 'oninput="'+config['func']+'();"');
        input.classList.add('zb-textarea');
        input.setAttribute('style', config['style'])

        box.appendChild(input);
    }

    this.addText = function (config){
        let box = document.getElementById('zbASSubBody');
        box.classList.add('zb-height-r100');
        let defaultValue = (config['defaultValue']) ? config['defaultValue'] : '';
        let tpl = '<div class = "zb-text" contenteditable="true" id="'+config['id']+'">'+defaultValue+'</div>';
        box.innerHTML = tpl;
    }

    this.getInputParams = function (id) {
        let str = document.getElementById(id).getAttribute('data-params');
        return JSON.parse(decodeURIComponent(str));
    }

    this.createNumberList = function (min, max, step=1) {
        let list = [];
        for (let i=min; i<=max; i+=step) {
            list.push(i);
        }
        return list;
    }

    this.repeatString = function (tplDom, arr, func=null) {
        if (!tplDom.length) {
            this.error('字符串长度为空');
            return;
        }

        if (arr.length === 0) {
            this.error('数据为空');
            return tplDom;
        }

        let tpl = tplDom;
        let out = '';
        for (let i=0; i<arr.length; i++) {
            if (typeof func === 'function') {
                arr[i] = func(arr[i]);
            }
            let map = arr[i];
            let tmp = tpl;
            for (let j in map) {
                let re = new RegExp('{' + j + '}', 'g');
                tmp = tmp.replace(re, map[j]);
            }

            let re = new RegExp('{_idx}', 'g');
            tmp = tmp.replace(re, parseInt(i)+1);

            out += tmp;
        }

        return out;
    };

    this.error = function(str) {
        console.log(str);
    }
}